package cn.lingyangwl.agile.msg.push.core.sender;

import cn.lingyangwl.agile.infra.*;
import cn.lingyangwl.agile.infra.module.file.model.rqrs.*;
import cn.lingyangwl.agile.msg.push.api.constatnts.*;
import cn.lingyangwl.agile.msg.push.api.model.content.*;
import cn.lingyangwl.agile.msg.push.api.model.rqrs.*;
import cn.lingyangwl.agile.msg.push.core.*;
import cn.lingyangwl.agile.msg.push.core.channel.websocket.*;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 推送到pc端
 * @author shenguangyang
 */
@Slf4j
@Service
public class PcSender implements MsgSender {
    @Resource
    private InfraApi infraApi;

    @Override
    public void sendMessage(PushTaskContext context) {
        context.setChannelCode(ChannelCodeEnum.PC);

        MsgParam msgParam = (MsgParam) context.getMsgParam();

        MsgSettings msgSettings = context.getMsgSettings();

        SitePushReq req = new SitePushReq();
        req.setContent(msgSettings.getRenderContent()).setBizType(msgParam.getBizType())
                .setTitle(msgParam.getTitle()).setPageUrl(msgParam.getPageUrl()).setVarData(msgSettings.getTplField());
        req.setNoticeCode(msgParam.getCode());
        req.setUserId(msgParam.getToUser());
        req.setLoginId(msgParam.getLoginId());

        if (Objects.nonNull(msgSettings.getMediaId())) {
            MediaMaterialResp material = infraApi.getMediaMaterial(msgSettings.getMediaId());
            if (log.isDebugEnabled()) {
                log.debug("push pc material: {}", JSON.toJSONString(material));
            }
            if (Objects.nonNull(material)) {
                req.setMediaType(material.getType());
                req.setMediaUrl(material.getUrl());
            }
        }
        log.info("push pc req: {}", JSON.toJSONString(req));
        PcChannelClient.sendMsg(req);
        context.setPushResult("success");
        context.setPushStatus(MsgPushStatus.SUCCESS);
    }

    @Override
    public ChannelTypeEnum channelType() {
        return ChannelTypeEnum.PC;
    }
}
